package sz.szsmk.citizencard.ui.dzsmkavtivity;


import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chenenyu.router.annotation.Route;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.ActivityBindCashCardBinding;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.IbaseBean;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThirdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetBankNameRes;
import sz.szsmk.citizencard.model.network.dzbean.res.SupportBankResponse;
import sz.szsmk.citizencard.mvp.contract.IBindCashCardContact;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.BindCashCardOldPresenter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.widget.GlideCircleTransform;
import sz.szsmk.citizencard.widget.SoftKeyboardStateHelper;

/**
 * Copyright (c)2018
 * author: zhf
 * created on: 2018/9/6 19:57
 * description:
 */
@Route("bindcashcard")
public class BindCashCardActivity extends IBaseActivity<BindCashCardOldPresenter, ActivityBindCashCardBinding>
        implements IBindCashCardContact.IBindCashCardView, SoftKeyboardStateHelper.SoftKeyboardStateListener {
    public static BindCashCardActivity instance;
    private static final int ACTION_TRUST = 1;
    private static final int ACTION_BIND = 2;
    private boolean isCheckBank = false;
    private boolean isCheck = false;
    private String channelId = "";
    private String bankMark = "1";
    private BottomSheetDialog bankDialog;
    private SoftKeyboardStateHelper softKeyboardStateHelper;

    private List<SupportBankResponse.DataBean> supportBankList = new ArrayList();
    private List<SupportBankResponse.DataBean> trustBankList = new ArrayList();

    /**
     * 弹窗操作action
     */
    private int currentAction;
    private String openId;
    private String mobile;
    private String userId;
    private String cardNo;
    private String token;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_bind_cash_card;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        instance = this;
        softKeyboardStateHelper = new SoftKeyboardStateHelper(this);
        softKeyboardStateHelper.addSoftKeyboardStateListener(this);
        setAuthText();
        openId = ACache.get(this).getAsString("openId");
        mobile = ACache.get(this).getAsString("mobile");
        userId = ACache.get(this).getAsString("userId");
        ACache.get(this).remove("channelId");
        ACache.get(this).put("channelId", "000003");
        mPresenter.dzsmkAgreement(openId, "000003");

        SupportBankResponse.DataBean trustItem2 = new SupportBankResponse.DataBean();
        trustItem2.setBankName("建设银行");
        trustItem2.setIconRes(R.drawable.icon_jianse_bank);
        trustBankList.add(trustItem2);

        SupportBankResponse.DataBean trustItem1 = new SupportBankResponse.DataBean();
        trustItem1.setBankName("南京银行");
        trustItem1.setIconRes(R.drawable.icon_nanjing_bank);
        trustBankList.add(trustItem1);
//        bankCardNumAddSpace(dataBinding.bindCardNoTxt, null);
//        dataBinding.trustCardSelect.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                showBankDialog(ACTION_TRUST);
//            }
//        });

        /**
         * 临时只有南京银行
         */
        isCheckBank = true;
        this.channelId = "";
//        dataBinding.trustCardTxt.setText(trustBankList.get(0).getBankName());
//        dataBinding.iconTrustCard.setVisibility(View.VISIBLE);
//        dataBinding.iconTrustCard.setImageResource(trustBankList.get(0).getIconRes());
//        隐藏选择托管银行弹窗
//        dataBinding.trustCardSelect.setVisibility(View.GONE);
//        dataBinding.btnRead.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (isChecked) {
//                    isCheck = true;
//                } else {
//                    isCheck = false;
//                }
//            }
//        });

//        dataBinding.bindCardSelect.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (isCheckBank) {
//                    String token = ACache.get(DaggerApplication.getIns()).getAsString("token");
//                    mPresenter.getSupportBankList(openId, "", token);
//                } else {
//                    Toast.makeText(BindCashCardActivity.this, "请选择托管银行", Toast.LENGTH_SHORT).show();
//                }
//
//            }
//        });

//        dataBinding.nextBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                cardNo = dataBinding.bindCardNoTxt.getText().toString().trim();
//                String replace = cardNo.replace(" ", "");
//                ACache.get(BindCashCardActivity.this).put("bankCardNumber", replace);
//                if (TextUtils.isEmpty(cardNo)) {
//                    Toast.makeText(BindCashCardActivity.this, "请输入银行卡号", Toast.LENGTH_SHORT).show();
//                    return;
//                } else {
//                    if (isCheck) {
//                        //查询银行卡 是否是银行卡
//                        mPresenter.checkBankNoValidation(replace, "", openId, token,selectBankCode);
//                    } else {
//                        Toast.makeText(BindCashCardActivity.this, "请点击协议", Toast.LENGTH_SHORT).show();
//                    }
//                }
//            }
//        });
//        dataBinding.textAgreement.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (bankMark.equals("0")) {
//                    Router.build("wordshow").with("word_name", "nanjing_argeement").go(BindCashCardActivity.this);
//                } else {
//                    Router.build("wordshow").with("word_name", "jianshe_argeement").go(BindCashCardActivity.this);
//                }
//            }
//        });
//        dataBinding.textAuth.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Router.build("wordshow").with("word_name", "nanjing_auth").go(BindCashCardActivity.this);
//            }
//        });
//
//        dataBinding.back.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                finish();
//            }
//        });
//        dataBinding.bindCardTxt.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                if(TextUtils.isEmpty(dataBinding.bindCardTxt.getText())){
//                    dataBinding.llLayout.setVisibility(View.VISIBLE);
//                }else{
//                    dataBinding.llLayout.setVisibility(View.GONE);
//                    dataBinding.bindCardNoTxt.setEnabled(true);
//                }
//            }
//        });
//
//        dataBinding.llLayout.setOnClickListener(v -> {
//            Toast.makeText(BindCashCardActivity.this,
//                            "请下拉选择开户银行，支持绑定工商银行、农业银行、中国银行、建设银行",Toast.LENGTH_LONG).show();
//        });
//
//        dataBinding.tvTitleTip.setText(Html.fromHtml("绑定支持的银行<font color='#EB5659'>借记</font>卡"));
    }


    private void bankCardNumAddSpace(final EditText mEditText, final TextView carSub_tv) {
        mEditText.addTextChangedListener(new TextWatcher() {

            int beforeTextLength = 0;
            int onTextLength = 0;
            boolean isChanged = false;

            int location = 0;// 记录光标的位置
            private char[] tempChar;
            private StringBuffer buffer = new StringBuffer();
            int konggeNumberB = 0;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeTextLength = s.length();
                if (buffer.length() > 0) {
                    buffer.delete(0, buffer.length());
                }
                konggeNumberB = 0;
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == ' ') {
                        konggeNumberB++;
                    }
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onTextLength = s.length();
                buffer.append(s.toString());
                if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
                    isChanged = false;
                    return;
                }
                isChanged = true;
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (carSub_tv != null) {
                    carSub_tv.setText(mEditText.getText());
                }
                if (isChanged) {
                    location = mEditText.getSelectionEnd();
                    int index = 0;
                    while (index < buffer.length()) {
                        if (buffer.charAt(index) == ' ') {
                            buffer.deleteCharAt(index);
                        } else {
                            index++;
                        }
                    }

                    index = 0;
                    int konggeNumberC = 0;
                    while (index < buffer.length()) {
                        if ((index == 4 || index == 9 || index == 14 || index == 19 || index == 24 || index == 29)) {
                            buffer.insert(index, ' ');
                            konggeNumberC++;
                        }
                        index++;
                    }

                    if (konggeNumberC > konggeNumberB) {
                        location += (konggeNumberC - konggeNumberB);
                    }

                    tempChar = new char[buffer.length()];
                    buffer.getChars(0, buffer.length(), tempChar, 0);
                    String str = buffer.toString();
                    if (location > str.length()) {
                        location = str.length();
                    } else if (location < 0) {
                        location = 0;
                    }

                    if (str.length() >= 23) {
                        str = str.substring(0, 23);
                        location = str.length();
                    }

                    mEditText.setText(str);
                    Editable etable = mEditText.getText();
                    Selection.setSelection(etable, location);
                    isChanged = false;
                }
            }
        });
    }

    private String selectBankCode="";

    /**
     * 展示银行选择的dialog
     *
     * @param type
     */
    private void showBankDialog(int type) {
        currentAction = type;
        bankDialog = new BottomSheetDialog(this);
        View bankListBottomSheet = LayoutInflater.from(this).inflate(R.layout.bank_list_dialog, null);
        RecyclerView bankRecycler = (RecyclerView) bankListBottomSheet.findViewById(R.id.bank_recycler);
        bankRecycler.setLayoutManager(new LinearLayoutManager(this));
        bankRecycler.setAdapter(new RecyclerView.Adapter<BankHolder>() {
            @Override
            public BankHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                return new BankHolder(LayoutInflater.from(BindCashCardActivity.this).inflate(R.layout.item_bank_list, parent, false));
            }

            @Override
            public void onBindViewHolder(BankHolder holder, final int position) {
                if (currentAction == ACTION_TRUST) {
                    holder.bankIcon.setImageResource(trustBankList.get(position).getIconRes());
                    holder.bankName.setText(trustBankList.get(position).getBankName());
                    holder.root.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (position == 0) {
                                ACache.get(BindCashCardActivity.this).put("channelId", "000003");
                                isCheckBank = true;
                                channelId = "000003";
                                bankMark = "1";
                                setAuthText();
                            } else if (position == 1) {
                                isCheckBank = true;
                                channelId = "000001";
                                bankMark = "0";
                                setAuthText();
                                ACache.get(BindCashCardActivity.this).put("channelId", "000001");
                            }
                            String openId = ACache.get(BindCashCardActivity.this).getAsString("openId");
                            L.e(Constant.TAG, "openid--:" + openId + "channelId" + channelId);
                            mPresenter.dzsmkAgreement(openId, channelId);
//                            dataBinding.trustCardTxt.setText(trustBankList.get(position).getBankName());
//                            dataBinding.iconTrustCard.setVisibility(View.VISIBLE);
//                            dataBinding.iconTrustCard.setImageResource(trustBankList.get(position).getIconRes());
                            bankDialog.dismiss();
                        }
                    });
                } else {
                    Glide.with(BindCashCardActivity.this)
                            .load(supportBankList.get(position).getBankIconUrl())
                            .override(100, 40)
                            .transform(new GlideCircleTransform(BindCashCardActivity.this))
                            .into(holder.bankIcon);
                    holder.bankName.setText(supportBankList.get(position).getBankName());
                    holder.root.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
//                            dataBinding.bindCardTxt.setText(supportBankList.get(position).getBankName());
//                            if (!TextUtils.isEmpty(supportBankList.get(position).getBankIconUrl())) {
//                                dataBinding.iconBindCard.setVisibility(View.VISIBLE);
//                                Glide.with(BindCashCardActivity.this)
//                                        .load(supportBankList.get(position).getBankIconUrl())
//                                        .override(100, 40)
//                                        .transform(new GlideCircleTransform(BindCashCardActivity.this))
//                                        .into(dataBinding.iconBindCard);
                                selectBankCode = supportBankList.get(position).getBankCode();
//                            } else
//                                dataBinding.iconBindCard.setVisibility(View.GONE);

                            bankDialog.dismiss();
                        }
                    });
                }
            }

            @Override
            public int getItemCount() {
                if (currentAction == ACTION_TRUST)
                    return trustBankList == null ? 0 : trustBankList.size();
                else
                    return supportBankList == null ? 0 : supportBankList.size();
            }
        });
        bankDialog.setContentView(bankListBottomSheet);
        bankDialog.show();
    }

    private void setAuthText() {
//        if (bankMark.equals("0")) {
//            dataBinding.textAuth.setVisibility(View.VISIBLE);
//        } else if (bankMark.equals("1")) {
//            dataBinding.textAuth.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void getSupportBankListFail() {

    }

    @Override
    public void getSupportBankListSucc(List<SupportBankResponse.DataBean> data) {
        supportBankList.clear();
        supportBankList.addAll(data);
        showBankDialog(ACTION_BIND);
    }

    @Override
    public void dzsmkAgreementFail(IbaseBean response) {

    }

    @Override
    public void dzsmkAgreementSucc(String channelId) {

        mPresenter.preAuthThird(openId, mobile, userId, channelId);
    }

    @Override
    public void preAuthThirdFail() {

    }

    @Override
    public void preAuthThirdSucc(PreAuthThirdRes preAuthRes) {
        if (preAuthRes != null) {
            token = preAuthRes.getData().getToken();
            ACache.get(this).remove("token");
            ACache.get(this).put("token", token);
        }
    }

    @Override
    public void getBankNameFail(GetBankNameRes getBankNameRes) {
        PubUtils.popTipOrWarn(this, getBankNameRes.getMessage());
    }

    @Override
    public void getBankNameSucc(GetBankNameRes getBankNameRes) {
        if (getBankNameRes != null) {
            String bankCode = getBankNameRes.getData().getBankCode();
            ACache.get(BindCashCardActivity.this).remove("bankCode");
            ACache.get(BindCashCardActivity.this).put("bankCode", bankCode);
            Intent intent = new Intent(BindCashCardActivity.this, AppendRealNameInfoActivity.class);
//                        Intent intent = new Intent(BindCashCardActivity.this, AppendRealNameInfoActivity.class);
            intent.putExtra("type", 0);
            startActivityForResult(intent, 123);
        }
    }

    //检测 银行卡 是否是信用卡
    @Override
    public void checkBankNoValidationFail(String msg) {
        Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        softKeyboardStateHelper.removeSoftKeyboardStateListener(this);
        isCheckBank = false;
    }

    @Override
    public void onSoftKeyboardOpened(int keyboardHeightInPx) {
//        dataBinding.adjustView.setVisibility(View.VISIBLE);
//        dataBinding.adjustView.post(new Runnable() {
//            @Override
//            public void run() {
//                dataBinding.scrollView.smoothScrollBy(0,
//                        Util.dpToPixel(BindCashCardActivity.this, 200));
//            }
//        });
    }

    @Override
    public void onSoftKeyboardClosed() {
//        dataBinding.adjustView.setVisibility(View.GONE);
    }

    /**
     * 银行选择holder
     */
    class BankHolder extends RecyclerView.ViewHolder {

        View root;
        ImageView bankIcon;
        TextView bankName;

        public BankHolder(View itemView) {
            super(itemView);
            root = itemView;
            bankIcon = (ImageView) root.findViewById(R.id.bank_icon);
            bankName = (TextView) root.findViewById(R.id.bank_name);
        }
    }
}
